package cn.kent.simple;

import java.util.ArrayList;
import java.util.List;

/**
 * 144. 二叉树的前序遍历
 * 前序遍历又叫先序遍历，也叫先根遍历
 * 根左右
 */
public class PreorderTraversal {
    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root != null) {
            return cycle(root, list);
        }
        return list;
    }

    private static List<Integer> cycle(TreeNode root, List<Integer> list) {
        if (root != null) list.add(root.val);
        if (root.left != null) cycle(root.left, list);
        if (root.right != null) cycle(root.right, list);
        return list;
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
